import Vue from 'vue'

const axios = require('axios')

const util = require('../util/util')

// let authId = util.getRandomId(32)

axios.defaults.withCredentials = true// 让ajax携带cookie

// axios.interceptors.request.use(function (config) {
//   if (/post/i.test(config.method)) {
//     if (typeof config.data === 'object' && typeof config.data.append === 'function') {
//       config.data.append('authId', authId)
//     } else {
//       config.data.authId = authId
//     }
//   } else if (/get/i.test(config.method)) {
//     config.param.authId = authId
//   }
//   // params.authId = authId;
//   return config
// }, function (error) {
//   return Promise.reject(error)
// })

axios.interceptors.response.use(function (res) {
  if (util.isObeject(res.data) && res.data.errno) {
    let e = new Error(res.data.errmsg)
    e.errno = res.data.errno
    return Promise.reject(e)
  }
  return res
}, function (error) {
  return Promise.reject(error)
})

export const apiPath = {
  test: '/api/test',

  GetSysFonts: '/api/GetSysFonts',
  ExecuteNonQuery: '/api/ExecuteNonQuery',
  ExecuteReaders: '/api/ExecuteReaders',
  ExecuteReader: '/api/ExecuteReader',
  ExecuteFirstLine: '/api/ExecuteFirstLine',
  ExecuteScalar: '/api/ExecuteScalar',
  DocumentConvertToImage: '/api/DocumentConvertToImage',
  HtmlExportWord: '/api/HtmlExportWord',
  // GetEvidenceMaterial: '/api/GetEvidenceMaterial',
  UploadFiles: '/api/UploadFiles',

  LoginVerification: '/api/ICE/LoginVerification',
  GetUnitTreeList: '/api/ICE/GetUnitTreeList',
  GetCaseList: '/api/ICE/GetCaseList',
  GetEvidenceMaterialCatalog: '/api/ICE/GetEvidenceMaterialCatalog',
  InitDatabaseFile: '/api/ICE/InitDatabaseFile',
  DownLoadEvidenceMaterial: '/api/ICE/DownLoadEvidenceMaterial',
  GetVersionRecords: '/api/ICE/GetVersionRecords',
  GetCaseInfo: '/api/ICE/GetCaseInfo',
  GetCases: '/api/ICE/GetCases',

  login: '/api/user/login',
  logout: '/api/user/logout',
  setUserInfo: '/api/user/setUserInfo',
  updateUserSocketId: '/api/user/updateUserSocketId',

  getCaseList: '/api/case/getCaseList',
  downloadCase: '/api/case/downloadCase',
  updateCase: '/api/case/updateCase',
  uploadCaseFile: '/api/case/uploadCaseFile',
  uploadFile: '/api/case/uploadFile',
  getCaseFileAccessorys: '/api/case/getCaseFileAccessorys',
  delCaseFileAccessory: '/api/case/delCaseFileAccessory',
  getCaseFileAccessoryByID: '/api/case/getCaseFileAccessoryByID',
  retoreCase: '/api/case/retoreCase',
  getCaseListByAJID: '/api/case/getCaseListByAJID',
  addAjxx: '/api/case/addAjxx',
  delAjxx: '/api/case/delAjxx',
  getEvidenceCatalog: '/api/case/getEvidenceCatalog',

  hmset: '/redis/hmset',

  getUpdateInfo: '/client/getUpdateInfo',
  uploadClient: '/client/uploadClient',
  uploadBrowser: '/client/uploadBrowser',
  getBrowserInfo: '/client/getBrowserInfo',
  deleteClient: '/client/deleteClient',

  getCurrentIndex: '/file/getCurrentIndex',
  uploadFileBySlice: '/file/uploadFileBySlice',
  getFileInfo: '/file/getFileInfo',

  getClassificationCode: '/api/server/getClassificationCode',
  addCourtRecord: '/api/server/addCourtRecord',
  getRecommendInfo: '/api/server/getRecommendInfo',
  getDataCategory: '/api/server/getDataCategory',
  // addDataCategory: '/api/server/addDataCategory',
  // delDataCategory: '/api/server/delDataCategory',
  getDataTag: '/api/server/getDataTag',
  // addDataTag: '/api/server/addDataTag',
  // delDataTag: '/api/server/delDataTag',
  addTrialData: '/api/server/addTrialData',
  getCaseData: '/api/server/getCaseData',
  getDataInfo: '/api/server/getDataInfo',
  getTrialStatistic: '/api/server/getTrialStatistic',
  getUseRankStatistic: '/api/server/getUseRankStatistic',
  getTrialCases: '/api/server/getTrialCases',
  addCaseReservation: '/api/server/addCaseReservation',
  delCaseReservation: '/api/server/delCaseReservation',

  getMyPublish: '/api/server/getMyPublish',
  getMyPublishStatistic: '/api/server/getMyPublishStatistic',
  getMySubscribe: '/api/server/getMySubscribe',
  getMySubscribeStatistic: '/api/server/getMySubscribeStatistic',
  getMyData: '/api/server/getMyData',
  getMyDataStatistic: '/api/server/getMyDataStatistic',
  getConcern: '/api/server/getConcern',

  getUserInfo: '/api/server/getUserInfo',
  addAttention: '/api/server/addAttention',
  delAttention: '/api/server/delAttention',
  getRecommendedFollowers: '/api/server/getRecommendedFollowers',
  getFavorite: '/api/server/getFavorite',
  getCourtStatisticByDate: '/api/server/getCourtStatisticByDate',
  getCourtCaseByDate: '/api/server/getCourtCaseByDate',
  addFavorite: '/api/server/addFavorite',
  delFavorite: '/api/server/delFavorite',
  getDynamicMessage: '/api/server/getDynamicMessage',
  getFollowerMessage: '/api/server/getFollowerMessage',
  getCorrelationMessage: '/api/server/getCorrelationMessage',
  getCourtRecord: '/api/server/getCourtRecord',
  getCaseTrajectory: '/api/server/getCaseTrajectory',
  getCourtConfirm: '/api/server/getCourtConfirm',
  addConfirmRecord: '/api/server/addConfirmRecord',
  addCaseComment: '/api/server/addCaseComment',
  getCaseComment: '/api/server/getCaseComment',

  getTrialNumberByArea: '/api/server/getTrialNumberByArea',
  getTrialNumberByDate: '/api/server/getTrialNumberByDate',

  getTrialDataByArea: '/api/server/getTrialDataByArea',
  getTrialDataByDate: '/api/server/getTrialDataByDate',

  getCaseCategoryByDate: '/api/server/getCaseCategoryByDate',

  getCaseChargesByDate: '/api/server/getCaseChargesByDate',

  getTrialAndCourt: '/api/server/getTrialAndCourt',
  // addTrialPlace: '/api/server/addTrialPlace',
  // delTrialPlace: '/api/server/delTrialPlace',
  // addCourt: '/api/server/addCourt',
  // delCourt: '/api/server/delCourt',

  getCharacteristicsDebate: '/api/server/getCharacteristicsDebate',
  getCaseAppointee: '/api/server/getCaseAppointee',
  getCaseRetrieval: '/api/server/getCaseRetrieval',

  // admin
  adminLogin: '/admin/user/adminLogin',
  adminLogout: '/admin/user/adminLogout',
  updateAdminUserInfo: '/admin/user/updateAdminUserInfo',
  setAdminUserInfo: '/admin/user/setAdminUserInfo',

  getLoginLog: '/admin/backstage/getLoginLog',
  adminGetDataCategory: '/admin/backstage/getDataCategory',
  addDataCategory: '/admin/backstage/addDataCategory',
  delDataCategory: '/admin/backstage/delDataCategory',
  adminGetDataTag: '/admin/backstage/getDataTag',
  addDataTag: '/admin/backstage/addDataTag',
  delDataTag: '/admin/backstage/delDataTag',
  addTrialPlace: '/admin/backstage/addTrialPlace',
  delTrialPlace: '/admin/backstage/delTrialPlace',
  addCourt: '/admin/backstage/addCourt',
  delCourt: '/admin/backstage/delCourt',
  adminGetTrialAndCourt: '/admin/backstage/getTrialAndCourt',

  // java
  // 统一业务接口
  getUserInfoByCode: '/UnifiedBusiness2/getUserInfoByCode',
  getUnitTreeList: '/UnifiedBusiness2/getUnitTreeList',
  downloadEvidenceMaterialCatalog: '/UnifiedBusiness2/downloadEvidenceMaterialCatalog',
  initDatabaseFile: '/UnifiedBusiness2/initDatabaseFile',
  getEvidenceMaterialByCode: '/UnifiedBusiness2/getEvidenceMaterialByCode',
  downLoadEvidenceMaterialByCodes: '/UnifiedBusiness2/downLoadEvidenceMaterialByCodes',
  GetEvidenceMaterial: '/UnifiedBusiness2/GetEvidenceMaterial',
  DownloadEvidenceCatalog: '/UnifiedBusiness2/DownloadEvidenceCatalog',

  // 案件数据库文件
  getVersionRecords: '/CaseDBFile/getVersionRecords', // 获取案件更新记录
  executeUpdates: '/CaseDBFile/executeUpdates', // 执行编辑语句
  executeQuerys: '/CaseDBFile/executeQuerys', // 执行查询语句
  executeScalar: '/CaseDBFile/executeScalar', // 执行查询语句

  // 案件文件信息
  getCaseFileInfoByCode: '/CaseFileInfo/getCaseFileInfoByCode', // 获取案件文件信息
  addCaseFileInfo: '/CaseFileInfo/addCaseFileInfo', // 添加案件文件信息
  addCaseUsedCount: '/CaseFileInfo/addCaseUsedCount', // 添加案件文件使用记录
  uploadFiles: '/CaseFileInfo/uploadFiles', // 添加案件文件使用记录
  zipCaseFile: '/CaseFileInfo/zipCaseFile', //
  downloadCaseFile: '/CaseFileInfo/downloadCaseFile', //
  getCaseAccessories: '/CaseFileInfo/getCaseAccessories' //
}

const $config = {
  url: '',
  method: '',
  baseURL: '',
  transformRequest: '',
  transformResponse: '',
  headers: '',
  params: '',
  paramsSerializer: '',
  data: '',
  timeout: '',
  responseType: '',
  xsrfCookieName: '',
  xsrfHeaderName: '',
  onUploadProgress: '',
  onDownloadProgress: '',
  maxContentLength: '',
  validateStatus: '',
  maxRedirects: '',
  socketPath: '',
  httpAgent: '',
  httpsAgent: '',
  proxy: '',
  cancelToken: ''
}

const requests = {}

async function request (url, params = {}, config = {}, id) {
  try {
    let _config = {
      url,
      method: config.method || 'GET',
      baseURL: config.baseURL,
      // transformRequest: [(data, headers) => data],
      // transformResponse: [(data) => data],
      headers: {'Content-Type': 'application/json'},
      params: '',
      // paramsSerializer: p => {
      //   let res = qs.stringify(p)
      //   console.log('stringify', res)
      // },
      data: '',
      // timeout: 1000,
      // responseType: 'json', // default
      // xsrfCookieName: 'XSRF-TOKEN', // default
      // xsrfHeaderName: 'X-XSRF-TOKEN', // default
      onUploadProgress: config.onUploadProgress || ((ev) => {
        let complete = ev.loaded / ev.total * 100 || 0
        // console.log("upload进度条", complete + '%');
        Vue.prototype.$eventBus.$emit('onUploadProgress', complete)
      }),
      onDownloadProgress: config.onDownloadProgress || ((ev) => {
        let complete = ev.loaded / ev.total * 100 || 0
        // console.log("download进度条", complete + '%');
        Vue.prototype.$eventBus.$emit('onDownloadProgress', complete)
      }),
      // maxContentLength: 2000,
      // validateStatus: function (status) {
      //   return status >= 200 && status < 300; // default
      // },
      // maxRedirects: 5, // default
      // socketPath: null, // default
      // httpAgent: new http.Agent({ keepAlive: true }),
      // httpsAgent: new https.Agent({ keepAlive: true }),
      // proxy: {
      //   host: '127.0.0.1',
      //   port: 9000,
      //   auth: {
      //     username: 'mikeymike',
      //     password: 'rapunz3l'
      //   }
      // },
      cancelToken: new axios.CancelToken(function (cancel) {
        if (id) requests[id] = cancel
      })
    }

    if (_config.method.toUpperCase() === 'GET') {
      _config.params = params
    } else if (_config.method.toUpperCase() === 'POST') {
      _config.data = params
    }

    let res = await axios.request(_config)
    if (res.data.status !== 0) throw new Error(`请求地址：${url}错误，错误原因${res.data.msg}`)
    return res.data.data
  } catch (e) {
    // if (axios.isCancel(e)) {
    //   console.log('Request canceled', e.message);
    // } else {
    // handle error
    if (e.errno === 666) {
      sessionStorage.removeItem('userInfo')
      try {
        Vue.prototype.$api.cancelAll()
        await Vue.prototype.$alert('未登录或登录超时，请重新登录！', '提示', {type: 'error'})
      } catch (e) {
      } finally {
        router.replace({path: '/Login', query: {r: Date.now()}})
      }
      return {errno: e.errno, errmsg: e.message}
    } else if (e.errno === 667) {
      sessionStorage.removeItem('adminUserInfo')
      try {
        await Vue.prototype.$alert('未登录或登录超时，请重新登录！', '提示-后台管理系统', {type: 'error'})
      } catch (e) {
      } finally {
        router.replace({path: '/AdminLogin', query: {r: Date.now()}})
      }
      return {errno: e.errno, errmsg: e.message}
    }
    throw e
    // }
  } finally {
    if (id) delete requests[id]
  }
}

export default (Vue, option = {}) => {
  let _httpUtil = {get: {}, post: {}}
  for (let api in apiPath) {
    let _config = {}
    _config.baseURL = option.baseURL

    _httpUtil.get[api] = async (params, config = {}, id = util.getRandomId()) => {
      if (id && requests.hasOwnProperty(id)) {
        throw new Error('id已存在')
      }

      for (let name in $config) {
        if (config[name]) _config[name] = config[name]
      }
      console.log(`【GET】：${apiPath[api]}`)
      try {
        return await request(apiPath[api], params, _config, id)
      } catch (e) {
        throw e
      }
    }
    _httpUtil.post[api] = async (params, config = {}, id = util.getRandomId()) => {
      if (id && requests.hasOwnProperty(id)) {
        throw new Error('id已存在')
      }
      for (let name in $config) {
        if (config[name]) _config[name] = config[name]
      }

      _config.method = 'POST'
      console.log(`【POST】：${apiPath[api]}`)
      try {
        return await request(apiPath[api], params, _config, id)
      } catch (e) {
        throw e
      }
    }
  }

  let cancel = (id, message = '') => {
    requests[id] && requests[id](message)
  }
  let cancelAll = (message = '') => {
    for (let id in requests) {
      requests[id] && requests[id](message)
    }
  }

  Vue.prototype.$api = {
    ..._httpUtil,
    cancel,
    cancelAll
  }
  // Vue.mixin({
  //   beforeDestroy() {
  // console.log('销毁前',this)
  //   }
  // });
}
